// repositories/subject.go
package repositories

import (
	"myapi/models"
)

// SubjectRepository 处理科目数据库操作
type SubjectRepository struct{}

// Create 创建新科目
func (r *SubjectRepository) Create(subject *models.Subject) error {
	return DB.Create(subject).Error
}

// FindByID 通过 ID 查找科目
func (r *SubjectRepository) FindByID(id uint) (*models.Subject, error) {
	var subject models.Subject
	err := DB.First(&subject, id).Error
	if err != nil {
		return nil, err
	}
	return &subject, nil
}

// FindAll 获取所有科目
func (r *SubjectRepository) FindAll(page, pageSize int) ([]models.Subject, int64, error) {
	var subjects []models.Subject
	var count int64
	offset := (page - 1) * pageSize
	// 获取总数
	if err := DB.Model(&models.Subject{}).Count(&count).Error; err != nil {
		return nil, 0, err
	}
	// 获取分页数据
	if err := DB.Offset(offset).Limit(pageSize).Find(&subjects).Error; err != nil {
		return nil, 0, err
	}
	return subjects, count, nil
}

// Update 更新科目信息
func (r *SubjectRepository) Update(subject *models.Subject) error {
	return DB.Save(subject).Error
}

// Delete 删除科目
func (r *SubjectRepository) Delete(id uint) error {
	return DB.Delete(&models.Subject{}, id).Error
}
